package com.fx.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
/*
 * 可以在类的级别直接限定访问
 * @PreAuthorize("hasRole('ROLE_ADMIN')")
 */
public class SecuController {

    @GetMapping("hello")
    public String hello(){
        return "hello";
    }

    //hasRole这里的角色前面不要加“ROLE_”前缀，security会自动加
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/admin/hello")
    public String hello2(){
        return "hello admin!";
    }
    @PreAuthorize("hasRole('user')")
    @GetMapping("/user/hello")
    public String hello3(){
        return "hello user";
    }

    @PreAuthorize("hasAuthority('fx:student:save')")
    @PostMapping("/student")
    public String addStudent(){
        return "add student";
    }
    @PreAuthorize("hasAuthority('fx:student:del')")
    @DeleteMapping("/student")
    public String delStudent(){
        return "delete student";
    }
    /*
     *  //仅仅a角色可以访问
     *  @Secured("ROLE_admin")//只有管理员角色才能删除用户
     *  @PreAuthorize("hasRole('ROLE_admin')")//等效于上面的语句
     *  a或b角色都可以
     *  @Secured({ "ROLE_admin", "ROLE_user" })
     *  @PreAuthorize("hasRole('ROLE_admin') or hasRole('ROLE_user')")//等效于上面的语句
     *
     *  除了@PreAuthorize，还有@PostAuthorize，两者的区别是：前者在进入方法之前检查给定的表达式，而后者在执行方法后验证它并且可能改变结果
     */
    @DeleteMapping("user")
    public String delUser(){
        return "删除了用户";
    }
    @GetMapping("user")
    public String getUser(){
        return "查询了user对象";
    }
}
